const Router = require('koa-router');
import { User } from "../lib/models/User"
import { responseResult, responseError, ERROR, responseOK } from "../lib/common/result"
let jsonwebtoken  = require('jsonwebtoken');
import { Cfg } from '../lib/common/config'
const router = new Router();

console.log("-----begin users router--------")
const SECRET = Cfg.selfOption.secret;

async function getToken(ctx){
  let query = ctx.request.body;
  if (query) {
    if (query.un && query.pwd) {
      let usr = await User.findOne({
        where: {
          uname: query.un
        }
      });
      if (usr) {
        if (usr.checkpassword(query.pwd)) {
          
          let userToken = { un: query.un, role: usr.roleId }
          let token = jsonwebtoken.sign(
            userToken,  // 加密userToken, 等同于上面解密的userToken
            SECRET,
            { expiresIn: '1h' }  // 有效时长1小时
          )
          responseResult(ctx, {usr,token});
          return;
        } else {
          responseError(ctx, ERROR.PASSWORD, "密码错误");
          return;
        }
      } else {
        responseError(ctx, ERROR.USERNAME, "用户不存在");
        return;
      }
    }
  }
  responseError(ctx, ERROR.PARAM, "参数不全");
  return;
}

router.post('/outapi/token', async (ctx) => {
  return getToken(ctx)
});

router.post('/outapi/login', async (ctx) => {
  return getToken(ctx)
});



router.get('/outapi/user', async (ctx) => {
  let user = await User.findByPk(ctx.request.body.un);
  if (!user) {
    responseError(ctx, ERROR.USERNAME, "用户不存在");
    return;
  }
  responseResult(ctx, user);
  return;
});

router.put('/outapi/user', async (ctx) => {
  if (!ctx.request.body || ctx.request.body.npwd === "") {
    responseError(ctx, ERROR.PARAM, "参数错误");
    return;
  }
  let user = await User.findByPk(ctx.request.body.un);
  if (!user) {
    responseError(ctx, ERROR.USERNAME, "用户不存在");
    return;
  }
  responseError(ctx, user.resetPwd(ctx.request.body.old, ctx.request.body.npwd));
  return;
});



router.delete('/outapi/user/:id', async (ctx) => {
  if (!ctx.body.params || !ctx.body.params.id) {
    responseError(ctx, ERROR.PARAM, "参数错误");
  } else {
    User.destroy({
      where: {
        uname: ctx.body.params.id
      }
    }).then(() => {
      responseOK(ctx);
    }).catch(err => {
      responseError(ctx, ERROR.USERNAME, err.toString());
    });
  }
  return;
});
router.put('/outapi/user/:id', async (ctx) => {
  let uid = ctx.body.params.id
  let did = ctx.body.query.did
  if (uid == undefined || uid == "" || uid == NaN) {
    responseError(ctx, ERROR.PARAM, "参数错误");
    return;
  }
  if (did == undefined || did == "" || did == NaN) {
    responseError(ctx, ERROR.PARAM, "参数错误");
    return;
  }
  let user = User.findByPk(uid);
  if (user) {
    user.departmentId = gid
    user.save()
  }
})
module.exports = router;
